/*
提交链接:https://leetcode.cn/problems/count-different-palindromic-subsequences/description/
730. [统计不同回文子序列]
赖德檀 2024/10/23
*/
  
class Solution {
public:
    const int MOD = 1000000007;

    int countPalindromicSubsequences(string s) {
        int n = s.size();
        vector<vector<int>> dp(n, vector<int>(n,0));
        vector<vector<int>> arr(n, vector<int>(4,0));
        vector<vector<int>> brr(n, vector<int>(4,0));
        for (int i = 0; i < n; i++) 
            dp[i][i] = 1;
        vector<int> crr(4, -1);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 4; j++) {
                brr[i][j] = crr[j];
            }
            crr[s[i] - 'a'] = i;
        }
        crr[0] = crr[1] = crr[2] = crr[3] = n;
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < 4; j++) {
                arr[i][j] = crr[j];
            }
            crr[s[i] - 'a'] = i;
        }
        for (int l = 2; l <= n; l++) {
            for (int i = 0; i + l <= n; i++) {
                int j = i + l - 1;
                if (s[i] == s[j]) {
                    int left = arr[i][s[i] - 'a'];
                    int rigth = brr[j][s[i] - 'a'];
                    if (left > rigth) {
                        dp[i][j] = (2 + dp[i + 1][j - 1] * 2) % MOD;
                    } else if (left == rigth) {
                        dp[i][j] = (1 + dp[i + 1][j - 1] * 2) % MOD;
                    } else {
                        dp[i][j] = (0LL + dp[i + 1][j - 1] * 2 - dp[left + 1][rigth - 1] + MOD) % MOD;
                    }
                } else {
                    dp[i][j] = (0LL + dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] + MOD) % MOD;
                }
            }
        }

        return dp[0][n - 1];
    }
};